{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Continuous training pipeline with Kubeflow Pipeline and AI Platform"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Learning Objectives:**\n",
    "1. Learn how to use Kubeflow Pipeline(KFP) pre-build components (BiqQuery, AI Platform training and predictions)\n",
    "1. Learn how to use KFP lightweight python components\n",
    "1. Learn how to build a KFP with these components\n",
    "1. Learn how to compile, upload, and run a KFP with the command line\n",
    "\n",
    "\n",
    "In this lab, you will build, deploy, and run a KFP pipeline that orchestrates **BigQuery** and **AI Platform** services to train, tune, and deploy a **scikit-learn** model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Understanding the pipeline design\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The workflow implemented by the pipeline is defined using a Python based Domain Specific Language (DSL). The pipeline's DSL is in the `covertype_training_pipeline.py` file that we will generate below.\n",
    "\n",
    "The pipeline's DSL has been designed to avoid hardcoding any environment specific settings like file paths or connection strings. These settings are provided to the pipeline code through a set of environment variables.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!grep 'BASE_IMAGE =' -A 5 pipeline/covertype_training_pipeline.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pipeline uses a mix of custom and pre-build components.\n",
    "\n",
    "- Pre-build components. The pipeline uses the following pre-build components that are included with the KFP distribution:\n",
    "    - [BigQuery query component](https://github.com/kubeflow/pipelines/tree/0.2.5/components/gcp/bigquery/query)\n",
    "    - [AI Platform Training component](https://github.com/kubeflow/pipelines/tree/0.2.5/components/gcp/ml_engine/train)\n",
    "    - [AI Platform Deploy component](https://github.com/kubeflow/pipelines/tree/0.2.5/components/gcp/ml_engine/deploy)\n",
    "- Custom components. The pipeline uses two custom helper components that encapsulate functionality not available in any of the pre-build components. The components are implemented using the KFP SDK's [Lightweight Python Components](https://www.kubeflow.org/docs/pipelines/sdk/lightweight-python-components/) mechanism. The code for the components is in the `helper_components.py` file:\n",
    "    - **Retrieve Best Run**. This component retrieves a tuning metric and hyperparameter values for the best run of a AI Platform Training hyperparameter tuning job.\n",
    "    - **Evaluate Model**. This component evaluates a *sklearn* trained model using a provided metric and a testing dataset.\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile ./pipeline/covertype_training_pipeline.py\n",
    "# Copyright 2019 Google LLC\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#      http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\"\"\"KFP orchestrating BigQuery and Cloud AI Platform services.\"\"\"\n",
    "\n",
    "import os\n",
    "\n",
    "from helper_components import evaluate_model\n",
    "from helper_components import retrieve_best_run\n",
    "from jinja2 import Template\n",
    "import kfp\n",
    "from kfp.components import func_to_container_op\n",
    "from kfp.dsl.types import Dict\n",
    "from kfp.dsl.types import GCPProjectID\n",
    "from kfp.dsl.types import GCPRegion\n",
    "from kfp.dsl.types import GCSPath\n",
    "from kfp.dsl.types import String\n",
    "from kfp.gcp import use_gcp_secret\n",
    "\n",
    "# Defaults and environment settings\n",
    "BASE_IMAGE = os.getenv('BASE_IMAGE')\n",
    "TRAINER_IMAGE = os.getenv('TRAINER_IMAGE')\n",
    "RUNTIME_VERSION = os.getenv('RUNTIME_VERSION')\n",
    "PYTHON_VERSION = os.getenv('PYTHON_VERSION')\n",
    "COMPONENT_URL_SEARCH_PREFIX = os.getenv('COMPONENT_URL_SEARCH_PREFIX')\n",
    "USE_KFP_SA = os.getenv('USE_KFP_SA')\n",
    "\n",
    "TRAINING_FILE_PATH = 'datasets/training/data.csv'\n",
    "VALIDATION_FILE_PATH = 'datasets/validation/data.csv'\n",
    "TESTING_FILE_PATH = 'datasets/testing/data.csv'\n",
    "\n",
    "# Parameter defaults\n",
    "SPLITS_DATASET_ID = 'splits'\n",
    "HYPERTUNE_SETTINGS = \"\"\"\n",
    "{\n",
    "    \"hyperparameters\":  {\n",
    "        \"goal\": \"MAXIMIZE\",\n",
    "        \"maxTrials\": 6,\n",
    "        \"maxParallelTrials\": 3,\n",
    "        \"hyperparameterMetricTag\": \"accuracy\",\n",
    "        \"enableTrialEarlyStopping\": True,\n",
    "        \"params\": [\n",
    "            {\n",
    "                \"parameterName\": \"max_iter\",\n",
    "                \"type\": \"DISCRETE\",\n",
    "                \"discreteValues\": [500, 1000]\n",
    "            },\n",
    "            {\n",
    "                \"parameterName\": \"alpha\",\n",
    "                \"type\": \"DOUBLE\",\n",
    "                \"minValue\": 0.0001,\n",
    "                \"maxValue\": 0.001,\n",
    "                \"scaleType\": \"UNIT_LINEAR_SCALE\"\n",
    "            }\n",
    "        ]\n",
    "    }\n",
    "}\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "# Helper functions\n",
    "def generate_sampling_query(source_table_name, num_lots, lots):\n",
    "    \"\"\"Prepares the data sampling query.\"\"\"\n",
    "\n",
    "    sampling_query_template = \"\"\"\n",
    "         SELECT *\n",
    "         FROM \n",
    "             `{{ source_table }}` AS cover\n",
    "         WHERE \n",
    "         MOD(ABS(FARM_FINGERPRINT(TO_JSON_STRING(cover))), {{ num_lots }}) IN ({{ lots }})\n",
    "         \"\"\"\n",
    "    query = Template(sampling_query_template).render(\n",
    "        source_table=source_table_name, num_lots=num_lots, lots=str(lots)[1:-1])\n",
    "\n",
    "    return query\n",
    "\n",
    "\n",
    "# Create component factories\n",
    "component_store = kfp.components.ComponentStore(\n",
    "    local_search_paths=None, url_search_prefixes=[COMPONENT_URL_SEARCH_PREFIX])\n",
    "\n",
    "bigquery_query_op = component_store.load_component('bigquery/query')\n",
    "mlengine_train_op = component_store.load_component('ml_engine/train')\n",
    "mlengine_deploy_op = component_store.load_component('ml_engine/deploy')\n",
    "retrieve_best_run_op = func_to_container_op(\n",
    "    retrieve_best_run, base_image=BASE_IMAGE)\n",
    "evaluate_model_op = func_to_container_op(evaluate_model, base_image=BASE_IMAGE)\n",
    "\n",
    "\n",
    "@kfp.dsl.pipeline(\n",
    "    name='Covertype Classifier Training',\n",
    "    description='The pipeline training and deploying the Covertype classifierpipeline_yaml'\n",
    ")\n",
    "def covertype_train(project_id,\n",
    "                    region,\n",
    "                    source_table_name,\n",
    "                    gcs_root,\n",
    "                    dataset_id,\n",
    "                    evaluation_metric_name,\n",
    "                    evaluation_metric_threshold,\n",
    "                    model_id,\n",
    "                    version_id,\n",
    "                    replace_existing_version,\n",
    "                    hypertune_settings=HYPERTUNE_SETTINGS,\n",
    "                    dataset_location='US'):\n",
    "    \"\"\"Orchestrates training and deployment of an sklearn model.\"\"\"\n",
    "\n",
    "    # Create the training split\n",
    "    query = generate_sampling_query(\n",
    "        source_table_name=source_table_name, num_lots=10, lots=[1, 2, 3, 4])\n",
    "\n",
    "    training_file_path = '{}/{}'.format(gcs_root, TRAINING_FILE_PATH)\n",
    "\n",
    "    create_training_split = bigquery_query_op(\n",
    "        query=query,\n",
    "        project_id=project_id,\n",
    "        dataset_id=dataset_id,\n",
    "        table_id='',\n",
    "        output_gcs_path=training_file_path,\n",
    "        dataset_location=dataset_location)\n",
    "\n",
    "    # Create the validation split\n",
    "    query = generate_sampling_query(\n",
    "        source_table_name=source_table_name, num_lots=10, lots=[8])\n",
    "\n",
    "    validation_file_path = '{}/{}'.format(gcs_root, VALIDATION_FILE_PATH)\n",
    "\n",
    "    create_validation_split = bigquery_query_op(\n",
    "        query=query,\n",
    "        project_id=project_id,\n",
    "        dataset_id=dataset_id,\n",
    "        table_id='',\n",
    "        output_gcs_path=validation_file_path,\n",
    "        dataset_location=dataset_location)\n",
    "\n",
    "    # Create the testing split\n",
    "    query = generate_sampling_query(\n",
    "        source_table_name=source_table_name, num_lots=10, lots=[9])\n",
    "\n",
    "    testing_file_path = '{}/{}'.format(gcs_root, TESTING_FILE_PATH)\n",
    "\n",
    "    create_testing_split = bigquery_query_op(\n",
    "        query=query,\n",
    "        project_id=project_id,\n",
    "        dataset_id=dataset_id,\n",
    "        table_id='',\n",
    "        output_gcs_path=testing_file_path,\n",
    "        dataset_location=dataset_location)\n",
    "\n",
    "    # Tune hyperparameters\n",
    "    tune_args = [\n",
    "        '--training_dataset_path',\n",
    "        create_training_split.outputs['output_gcs_path'],\n",
    "        '--validation_dataset_path',\n",
    "        create_validation_split.outputs['output_gcs_path'], '--hptune', 'True'\n",
    "    ]\n",
    "\n",
    "    job_dir = '{}/{}/{}'.format(gcs_root, 'jobdir/hypertune',\n",
    "                                kfp.dsl.RUN_ID_PLACEHOLDER)\n",
    "\n",
    "    hypertune = mlengine_train_op(\n",
    "        project_id=project_id,\n",
    "        region=region,\n",
    "        master_image_uri=TRAINER_IMAGE,\n",
    "        job_dir=job_dir,\n",
    "        args=tune_args,\n",
    "        training_input=hypertune_settings)\n",
    "\n",
    "    # Retrieve the best trial\n",
    "    get_best_trial = retrieve_best_run_op(\n",
    "            project_id, hypertune.outputs['job_id'])\n",
    "\n",
    "    # Train the model on a combined training and validation datasets\n",
    "    job_dir = '{}/{}/{}'.format(gcs_root, 'jobdir', kfp.dsl.RUN_ID_PLACEHOLDER)\n",
    "\n",
    "    train_args = [\n",
    "        '--training_dataset_path',\n",
    "        create_training_split.outputs['output_gcs_path'],\n",
    "        '--validation_dataset_path',\n",
    "        create_validation_split.outputs['output_gcs_path'], '--alpha',\n",
    "        get_best_trial.outputs['alpha'], '--max_iter',\n",
    "        get_best_trial.outputs['max_iter'], '--hptune', 'False'\n",
    "    ]\n",
    "\n",
    "    train_model = mlengine_train_op(\n",
    "        project_id=project_id,\n",
    "        region=region,\n",
    "        master_image_uri=TRAINER_IMAGE,\n",
    "        job_dir=job_dir,\n",
    "        args=train_args)\n",
    "\n",
    "    # Evaluate the model on the testing split\n",
    "    eval_model = evaluate_model_op(\n",
    "        dataset_path=str(create_testing_split.outputs['output_gcs_path']),\n",
    "        model_path=str(train_model.outputs['job_dir']),\n",
    "        metric_name=evaluation_metric_name)\n",
    "\n",
    "    # Deploy the model if the primary metric is better than threshold\n",
    "    with kfp.dsl.Condition(eval_model.outputs['metric_value'] > evaluation_metric_threshold):\n",
    "        deploy_model = mlengine_deploy_op(\n",
    "        model_uri=train_model.outputs['job_dir'],\n",
    "        project_id=project_id,\n",
    "        model_id=model_id,\n",
    "        version_id=version_id,\n",
    "        runtime_version=RUNTIME_VERSION,\n",
    "        python_version=PYTHON_VERSION,\n",
    "        replace_existing_version=replace_existing_version)\n",
    "\n",
    "    # Configure the pipeline to run using the service account defined\n",
    "    # in the user-gcp-sa k8s secret\n",
    "    if USE_KFP_SA == 'True':\n",
    "        kfp.dsl.get_pipeline_conf().add_op_transformer(\n",
    "              use_gcp_secret('user-gcp-sa'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The custom components execute in a container image defined in `base_image/Dockerfile`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat base_image/Dockerfile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The training step in the pipeline employes the AI Platform Training component to schedule a  AI Platform Training job in a custom training container. The custom training image is defined in `trainer_image/Dockerfile`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat trainer_image/Dockerfile"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building and deploying the pipeline\n",
    "\n",
    "Before deploying to AI Platform Pipelines, the pipeline DSL has to be compiled into a pipeline runtime format, also refered to as a pipeline package.  The runtime format is based on [Argo Workflow](https://github.com/argoproj/argo), which is expressed in YAML. \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Configure environment settings\n",
    "\n",
    "Update  the below constants  with the settings reflecting your lab environment. \n",
    "\n",
    "- `REGION` - the compute region for AI Platform Training and Prediction\n",
    "- `ARTIFACT_STORE` - the GCS bucket created during installation of AI Platform Pipelines. The bucket name will be similar to `qwiklabs-gcp-xx-xxxxxxx-kubeflowpipelines-default`.\n",
    "- `ENDPOINT` - set the `ENDPOINT` constant to the endpoint to your AI Platform Pipelines instance. Then endpoint to the AI Platform Pipelines instance can be found on the [AI Platform Pipelines](https://console.cloud.google.com/ai-platform/pipelines/clusters) page in the Google Cloud Console.\n",
    "\n",
    "1. Open the **SETTINGS** for your instance\n",
    "2. Use the value of the `host` variable in the **Connect to this Kubeflow Pipelines instance from a Python client via Kubeflow Pipelines SKD** section of the **SETTINGS** window.\n",
    "\n",
    "Run gsutil ls without URLs to list all of the Cloud Storage buckets under your default project ID."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!gsutil ls"
   ]
  },
  {
   "source": [
    "**HINT:** \n",
    "\n",
    "For **ENDPOINT**, use the value of the `host` variable in the **Connect to this Kubeflow Pipelines instance from a Python client via Kubeflow Pipelines SDK** section of the **SETTINGS** window.\n",
    "\n",
    "For **ARTIFACT_STORE_URI**, copy the bucket name which starts with the qwiklabs-gcp-xx-xxxxxxx-kubeflowpipelines-default prefix from the previous cell output. Your copied value should look like **'gs://qwiklabs-gcp-xx-xxxxxxx-kubeflowpipelines-default'**"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "REGION = 'us-central1' # TO DO: REPLACE WITH YOUR AI PLATFORM PIPELINES REGION\n",
    "ENDPOINT = '337dd39580cbcbd2-dot-us-central2.pipelines.googleusercontent.com' # TO DO: REPLACE WITH YOUR ENDPOINT\n",
    "ARTIFACT_STORE_URI = 'gs://qwiklabs-gcp-xx-xxxxxxx-kubeflowpipelines-default'  # TO DO: REPLACE WITH YOUR ARTIFACT_STORE NAME \n",
    "PROJECT_ID = !(gcloud config get-value core/project)\n",
    "PROJECT_ID = PROJECT_ID[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Build the trainer image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "IMAGE_NAME='trainer_image'\n",
    "TAG='latest'\n",
    "TRAINER_IMAGE='gcr.io/{}/{}:{}'.format(PROJECT_ID, IMAGE_NAME, TAG)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### **Note**: Please ignore any **incompatibility ERROR** that may appear for the packages visions as it will not affect the lab's functionality."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!gcloud builds submit --timeout 15m --tag $TRAINER_IMAGE trainer_image"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Build the base image for custom components"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "IMAGE_NAME='base_image'\n",
    "TAG='latest'\n",
    "BASE_IMAGE='gcr.io/{}/{}:{}'.format(PROJECT_ID, IMAGE_NAME, TAG)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!gcloud builds submit --timeout 15m --tag $BASE_IMAGE base_image"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compile the pipeline\n",
    "\n",
    "You can compile the DSL using an API from the **KFP SDK** or using the **KFP** compiler.\n",
    "\n",
    "To compile the pipeline DSL using the **KFP** compiler."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Set the pipeline's compile time settings\n",
    "\n",
    "The pipeline can run using a security context of the GKE default node pool's service account or the service account defined in the `user-gcp-sa` secret of the Kubernetes namespace hosting KFP. If you want to use the `user-gcp-sa` service account you change the value of `USE_KFP_SA` to `True`.\n",
    "\n",
    "Note that the default AI Platform Pipelines configuration does not define the `user-gcp-sa` secret."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "USE_KFP_SA = False\n",
    "\n",
    "COMPONENT_URL_SEARCH_PREFIX = 'https://raw.githubusercontent.com/kubeflow/pipelines/0.2.5/components/gcp/'\n",
    "RUNTIME_VERSION = '1.15'\n",
    "PYTHON_VERSION = '3.7'\n",
    "\n",
    "%env USE_KFP_SA={USE_KFP_SA}\n",
    "%env BASE_IMAGE={BASE_IMAGE}\n",
    "%env TRAINER_IMAGE={TRAINER_IMAGE}\n",
    "%env COMPONENT_URL_SEARCH_PREFIX={COMPONENT_URL_SEARCH_PREFIX}\n",
    "%env RUNTIME_VERSION={RUNTIME_VERSION}\n",
    "%env PYTHON_VERSION={PYTHON_VERSION}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Use the CLI compiler to compile the pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!dsl-compile --py pipeline/covertype_training_pipeline.py --output covertype_training_pipeline.yaml"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is the `covertype_training_pipeline.yaml` file. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!head covertype_training_pipeline.yaml"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Set the command fields in the pipeline YAML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!sed -i 's/\\\"command\\\": \\[\\]/\\\"command\\\": \\[python, -u, -m, kfp_component.launcher\\]/g' covertype_training_pipeline.yaml"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat covertype_training_pipeline.yaml | grep \"component.launcher\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should see 6 lines in the output that were modified by the sed command."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Deploy the pipeline package"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "PIPELINE_NAME='covertype_continuous_training'\n",
    "\n",
    "!kfp --endpoint $ENDPOINT pipeline upload \\\n",
    "-p $PIPELINE_NAME \\\n",
    "covertype_training_pipeline.yaml"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Submitting pipeline runs\n",
    "\n",
    "You can trigger pipeline runs using an API from the KFP SDK or using KFP CLI. To submit the run using KFP CLI, execute the following commands. Notice how the pipeline's parameters are passed to the pipeline run.\n",
    "\n",
    "### List the pipelines in AI Platform Pipelines"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!kfp --endpoint $ENDPOINT pipeline list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Submit a run\n",
    "\n",
    "Find the ID of the `covertype_continuous_training` pipeline you uploaded in the previous step and update the value of `PIPELINE_ID` .\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "PIPELINE_ID='0918568d-758c-46cf-9752-e04a4403cd84' # TO DO: REPLACE WITH YOUR PIPELINE ID "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "EXPERIMENT_NAME = 'Covertype_Classifier_Training'\n",
    "RUN_ID = 'Run_001'\n",
    "SOURCE_TABLE = 'covertype_dataset.covertype'\n",
    "DATASET_ID = 'splits'\n",
    "EVALUATION_METRIC = 'accuracy'\n",
    "EVALUATION_METRIC_THRESHOLD = '0.69'\n",
    "MODEL_ID = 'covertype_classifier'\n",
    "VERSION_ID = 'v01'\n",
    "REPLACE_EXISTING_VERSION = 'True'\n",
    "\n",
    "GCS_STAGING_PATH = '{}/staging'.format(ARTIFACT_STORE_URI)"
   ]
  },
  {
   "source": [
    "Run the pipeline using the `kfp` command line by retrieving the variables from the environment to pass to the pipeline where:\n",
    "\n",
    "- EXPERIMENT_NAME is set to the experiment used to run the pipeline. You can choose any name you want. If the experiment does not exist it will be created by the command\n",
    "- RUN_ID is the name of the run. You can use an arbitrary name\n",
    "- PIPELINE_ID is the id of your pipeline. Use the value retrieved by the   `kfp pipeline list` command\n",
    "- GCS_STAGING_PATH is the URI to the Cloud Storage location used by the pipeline to store intermediate files. By default, it is set to the `staging` folder in your artifact store.\n",
    "- REGION is a compute region for AI Platform Training and Prediction. \n",
    "\n",
    "You should be already familiar with these and other parameters passed to the command. If not go back and review the pipeline code."
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!kfp --endpoint $ENDPOINT run submit \\\n",
    "-e $EXPERIMENT_NAME \\\n",
    "-r $RUN_ID \\\n",
    "-p $PIPELINE_ID \\\n",
    "project_id=$PROJECT_ID \\\n",
    "gcs_root=$GCS_STAGING_PATH \\\n",
    "region=$REGION \\\n",
    "source_table_name=$SOURCE_TABLE \\\n",
    "dataset_id=$DATASET_ID \\\n",
    "evaluation_metric_name=$EVALUATION_METRIC \\\n",
    "evaluation_metric_threshold=$EVALUATION_METRIC_THRESHOLD \\\n",
    "model_id=$MODEL_ID \\\n",
    "version_id=$VERSION_ID \\\n",
    "replace_existing_version=$REPLACE_EXISTING_VERSION"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Monitoring the run\n",
    "\n",
    "You can monitor the run using KFP UI. Follow the instructor who will walk you through the KFP UI and monitoring techniques.\n",
    "\n",
    "To access the KFP UI in your environment use the following URI:\n",
    "\n",
    "https://[ENDPOINT]\n",
    "\n",
    "\n",
    "**NOTE that your pipeline run may fail due to the bug in a BigQuery component that does not handle certain race conditions. If you observe the pipeline failure, re-run the last cell of the notebook to submit another pipeline run or retry the run from the KFP UI**\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font size=-1>Licensed under the Apache License, Version 2.0 (the \\\"License\\\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \\\"AS IS\\\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and limitations under the License.</font>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
